import { Injectable } from '@nestjs/common';
import { CouponSort_Create_Dto, CouponSort_Update_Dto } from './assets/couponSort.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { CouponSort } from './assets/couponSort.entity';
import { Repository } from 'typeorm';
import { CouponSort_Find_Dto } from './assets/couponSort.dto';
import {
  util_Db_Add,
  util_Db_Update,
  util_Db_Delete,
  util_Db_AddAnyWhere,
  util_Db_PageList,
} from '@/common/util/db';

@Injectable()
export class CouponSort_Service {
  constructor(
    @InjectRepository(CouponSort)
    private couponSort_Repository: Repository<CouponSort>,
  ) {}

  async couponSort_Create(body: CouponSort_Create_Dto) {
    return await util_Db_Add({
      createDto: body,
      repository: this.couponSort_Repository,
    });
  }

  async couponSort_FindByPage(query: CouponSort_Find_Dto) {
    return await util_Db_PageList<CouponSort>({
      queryBuilder: this.couponSort_Repository.createQueryBuilder('couponSort'),
      query,
    });
  }

  async couponSort_Adm_FindAllSelect(query: CouponSort_Find_Dto) {
    return await util_Db_AddAnyWhere({
      queryBuilder: this.couponSort_Repository
        .createQueryBuilder('couponSort')
        .select(['couponSort.id AS id', 'couponSort.couponSortName AS name']),
      obj: { couponSortName: query.couponSortName },
    }).getRawMany();
  }

  async couponSort_Update(body: CouponSort_Update_Dto) {
    return await util_Db_Update({
      findOne: () => this.couponSort_FindOneById(body.id),
      updateDto: body,
      repository: this.couponSort_Repository,
    });
  }

  async couponSort_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.couponSort_FindOneById(id),
      id,
      repository: this.couponSort_Repository,
    });
  }

  async couponSort_FindOneById(id: number) {
    return await this.couponSort_Repository
      .createQueryBuilder('couponSortSort')
      .andWhere(`couponSortSort.id = :id`, { id: id })
      .getOne();
  }
}
